#!/bin/bash

# 智能排课系统 - 前端部署脚本
# 目标服务器：172.16.29.198

echo "========================================="
echo "智能排课系统 - 前端部署"
echo "========================================="

# 1. 打包前端
echo ""
echo "【步骤 1/4】打包前端项目..."
npm run build
if [ $? -ne 0 ]; then
    echo "❌ 打包失败！"
    exit 1
fi
echo "✅ 打包完成"

# 2. 压缩dist文件夹
echo ""
echo "【步骤 2/4】压缩dist文件夹..."
cd dist
tar -czf ../frontend-dist.tar.gz *
cd ..
echo "✅ 压缩完成"

# 3. 上传到服务器
echo ""
echo "【步骤 3/4】上传到服务器..."
scp frontend-dist.tar.gz root@172.16.29.198:/tmp/
if [ $? -ne 0 ]; then
    echo "❌ 上传失败！请检查SSH连接"
    exit 1
fi
echo "✅ 上传完成"

# 4. 上传 Nginx 配置
echo ""
echo "【步骤 4/6】上传 Nginx 配置..."
scp nginx.conf root@172.16.29.198:/tmp/paike-nginx.conf
echo "✅ 上传完成"

# 5. 在服务器上部署
echo ""
echo "【步骤 5/6】在服务器上部署..."
ssh root@172.16.29.198 << 'ENDSSH'
# 创建部署目录
mkdir -p /opt/paike/frontend

# 解压
cd /opt/paike/frontend
rm -rf *
tar -xzf /tmp/frontend-dist.tar.gz

# 配置 Nginx
cp /tmp/paike-nginx.conf /etc/nginx/conf.d/paike.conf

# 测试 Nginx 配置
nginx -t

# 重启 Nginx
systemctl restart nginx

# 清理
rm -f /tmp/frontend-dist.tar.gz
rm -f /tmp/paike-nginx.conf

echo "✅ 前端部署完成！"
echo "访问地址: http://172.16.29.198"
ENDSSH

# 6. 验证部署
echo ""
echo "【步骤 6/6】验证部署..."
curl -s -o /dev/null -w "HTTP状态码: %{http_code}\n" http://172.16.29.198

# 清理本地临时文件
rm -f frontend-dist.tar.gz

echo ""
echo "========================================="
echo "✅ 部署成功！"
echo "========================================="
echo "前端地址: http://172.16.29.198"
echo "后端地址: http://172.16.29.198:8090"
echo "========================================="

